package com.ys.controller.api.business;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.business.TpAnalysisDailyTarget;
import com.ys.entity.business.TpShopRegisterPhaseRecord;
import com.ys.entity.sys.YsCol;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.DateUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tpAnalysisDailyTarget")
public class ApiInterTpAnalysisDailyTargetController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTpAnalysisDailyTargetController.class);
    private static Long MENU_ID = 72L;
    private static Long MENU_ID_E = 74L;

    @Autowired
    private CommonApiService<TpAnalysisDailyTarget> commonApiService;
    //@Autowired
    //private TpAnalysisDailyTargetSetService tpAnalysisDailyTargetSetService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TpAnalysisDailyTarget setSeachSql(TpAnalysisDailyTarget cond,int resultType){
        /*
        cond.addField("O.VGsJc AS vGsJc");//运营公司简称
        cond.addField("PO.VGsJc AS pVGsJc");//上级运营公司简称
        //cond.addField("O.VGsBm AS vGsBm");//运营公司编码
        cond.addField("O.CUser + '/' + O.CUserName AS operateUser ");//运营人工号/姓名
        cond.addField("O.CDeptName AS vYyJb");//运营组别，所属部门
        cond.addField("CASE WHEN PO.CUser IS NULL THEN '' ELSE PO.CUser + '/' + PO.CUserName END pOperateUser ");//上级运营人工号/姓名
        cond.addField("PO.CDeptName AS pVYyJb ");//运营组别上级，所属部门上级
        cond.addField("S.ShopName AS shopName ");//店铺名称
        cond.addField("S.RegionName AS regionName ");//店铺区域；countryName国家名称
        cond.addField("S.FirstSaleDay AS firstSaleDay ");//开售日期
         */

        cond.addField("A.CUser + '/' + A.CUserName AS operateUser ");//运营人工号/姓名
        cond.addField("A.CDeptName AS vYyJb");//运营组别，所属部门
        cond.addField("CASE WHEN A.PCUser IS NULL THEN '' ELSE A.PCUser + '/' + A.PCUserName END pOperateUser ");//上级运营人工号/姓名
        cond.addField("A.CDeptName AS pVYyJb ");//运营组别上级，所属部门上级
        if(resultType==0){
            cond.addField("D.DailyTarget AS dailyTarget ");//日均目标
        }else {
            cond.addField("D.ElaborateDailyTarget AS elaborateDailyTarget ");//日均目标
        }

        //关联日均目标维护表
        cond.addLeftJoin("kjecp_report.dbo.TP_AnalysisDailyTargetSet D ON D.Id = A.TargetSetId ");

        cond.where("A.ProductType = "+ resultType);

        //过滤累计订单数大于0的
        cond.where("A.AccumulateOrder>0 AND A.TargetSetId IS NOT NULL");
        //排序
        cond.setOrderby("A.InfoTime DESC,A.VGsBm ASC");
        return  cond;
    }

    //处理返回的数据
    public List setList(List<Map<String, Object>> resDate,int resultType){
        List<Map<String, Object>> tableDate = new ArrayList();

        resDate.forEach(setItem->{
            String monthStr = setItem.get("infoTime").toString();
            int lastDay = new DateUtil().getMonthLastDay(monthStr);//获取月份的天数
            int dailyTarget = resultType==0?Integer.parseInt(setItem.get("dailyTarget").toString()):Integer.parseInt(setItem.get("elaborateDailyTarget").toString());//日均目标
            setItem.put("monthTarget",lastDay*dailyTarget);//计算月目标
            setItem.put("timeScheduleCount",setItem.get("timeSchedule").toString()+ "%");//时间进度

            BigDecimal growthRateNum = (BigDecimal) setItem.get("growthRate");
            //BigDecimal elaborateGrowthRateNum = (BigDecimal) setItem.get("elaborateGrowthRate");
            setItem.put("growthRate",String.format("%.2f", growthRateNum.floatValue()*100)+"%");
            //setItem.put("elaborateGrowthRate",String.format("%.2f", elaborateGrowthRateNum.floatValue()*100)+"%");

            tableDate.add(setItem);
        });

        return tableDate;
    }

    //根据类型获取返回数据
    public LayuiTableVoJA searchByType(TpAnalysisDailyTarget cond,int resultType){
        cond = setSeachSql(cond,resultType);
        //权限
        if(resultType==0){
    		cond = commonApiService.dataAuth(MENU_ID, cond);
        }else {
    		cond = commonApiService.dataAuth(MENU_ID_E, cond);
        }

        LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
        //合计
        {
            JSONObject JO = new JSONObject();
            //计算累计
            cond.setMainTable("kjecp_report.dbo.TP_AnalysisDailyTarget");
            // 累计当日
            JO.put("todayOrder", cond.setFields("ISNULL(SUM(A.TodayOrder),0)").sumDecimal());
            // 累计订单
            JO.put("accumulateOrder", cond.setFields("ISNULL(SUM(A.AccumulateOrder),0)").sumDecimal());
            // 当日金额
            JO.put("todayAmount", cond.setFields("ISNULL(SUM(A.TodayAmount),0)").sumDecimal());
            // 累计订单金额
            JO.put("accumulateAmount", cond.setFields("ISNULL(SUM(A.AccumulateAmount),0)").sumDecimal());
            // 当日金额(原货币)
            JO.put("todayAmountLocal", cond.setFields("ISNULL(SUM(A.TodayAmountLocal),0)").sumDecimal());
            // 累计订单金额(原货币)
            JO.put("accumulateAmountLocal", cond.setFields("ISNULL(SUM(A.AccumulateAmountLocal),0)").sumDecimal());

            tableVoJA.setTotalRow(JO);
        }
        //获取
        JSONArray tableVoJAData = tableVoJA.getData();
        //转换
        List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
        List<Map<String, Object>> resListNew = new ArrayList();
        resList.forEach(item-> resListNew.add(item));

        //处理数据
        resList = setList(resListNew,resultType);
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
        tableVoJA.setData(jsonArray);


        return tableVoJA;
    }



    /**
     * 查询
     */
    @RequiresPermissions("tpAnalysisDailyTarget:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TpAnalysisDailyTarget cond
    ){
        try {
            return searchByType(cond,0);
        }catch (Exception e){
            logger.error("查询运营日报目标表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 查询-精品
     */
    //@RequiresPermissions("tpAnalysisDailyTarget:view")
    @RequestMapping("/searchByElaborate")
    @ResponseBody
    public LayuiTableVoJA searchByElaborate(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TpAnalysisDailyTarget cond
    ){
        try {
            return searchByType(cond,1);
        }catch (Exception e){
            logger.error("查询运营日报目标表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    //根据类型获取返回导出数据
    public UploadDto exportByType(TpAnalysisDailyTarget cond,int setType){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond,setType);
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            listData = setList(listData,setType);

            Long menuId = setType==0?MENU_ID:MENU_ID_E;

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .where("A.Code != 'ope'")
                    .setOrderby("A.SortNo asc")
                    .queryList();

            ExportExcelUtils<TpShopRegisterPhaseRecord> util = new ExportExcelUtils<>(new TpShopRegisterPhaseRecord());

            String toFilePath = util.exportExcel(listData, listField, "运营日报目标表");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return dto;
        }catch (Exception e){
            logger.error("导出运营日报目标表出错：",e.getMessage(),e);
            return null;
        }

    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TpAnalysisDailyTarget cond){
        try {
            UploadDto dto =exportByType(cond,0);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出运营日报目标表出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }
    /**
     * 导出-精品
     */
    @RequestMapping("/exportByElaborate")
    @ResponseBody
    public R exportByElaborate(@ModelAttribute TpAnalysisDailyTarget cond){
        try {
            UploadDto dto =exportByType(cond,1);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出运营日报目标表出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }





}